package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import example.AppConstants;
import example.model.Customer;
import finelProject.MyAppConstants;
import finelProject.model.Messages;

/**
 * Servlet implementation class GetTenLastMessages
 */
public class GetTenLastMessages extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetTenLastMessages() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Context context;
		Collection<Messages> MessagesResult = new ArrayList<Messages>(); 
		try {
			context = new InitialContext();
			BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();
			
			PreparedStatement stmt;
			try{
				stmt = conn.prepareStatement(MyAppConstants.GET_TEN_LAST_MESSAGES);
				ResultSet rs = stmt.executeQuery();
				
				while (rs.next()){
					Messages current = new Messages(rs.getString(2),rs.getInt(3),rs.getTimestamp(4),rs.getString(5),rs.getString(1),rs.getInt(7),rs.getInt(6),rs.getDouble(8),rs.getString(9));
					MessagesResult.add(current);
				}
				rs.close();
				stmt.close();
			}catch(SQLException e){
				getServletContext().log("Error while querying for customers", e);
	    		response.sendError(500);//internal server error
			}
			conn.close();
			Gson gson = new Gson();
        	//convert from customers collection to json
        	String MessagesJsonResult = gson.toJson(MessagesResult, MyAppConstants.MESSAGES_COLLECTION);

        	PrintWriter writer = response.getWriter();
        	writer.println(MessagesJsonResult);
        	writer.close();
			context.close();
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
